package com.camus.algorithm.impl;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.camus.algorithm.SubsetAlgorithm4Int;

/**
 * 简单递归算法求目标和的子集
 * 
 * @author jie.deng
 *
 */
public class SubsetAlgorithmOfRecursion4Int implements SubsetAlgorithm4Int {
	
	private static final Logger log = LoggerFactory.getLogger(SubsetAlgorithmOfRecursion4Int.class);

	@Override
	public int[] findSubsetOfTargetSum(int[] candidateArr, int target) {
		counter.remove();

		// 逐层递归
		int[] subsetArr = findSubsetOfTargetSum(candidateArr, target, 0, new boolean[candidateArr.length], 0);

		log.info("入参paramArr={},target={},resultArr={},时间复杂度={}", Arrays.toString(candidateArr), target, subsetArr,
				counter.get());
		return subsetArr == null || subsetArr.length == 0 ? null : subsetArr;
	}

	/**
	 * 
	 * @param candidateArr
	 * @param target
	 * @param nextIdx
	 * @param flagArr
	 * @param curSum
	 * @return
	 */
	public int[] findSubsetOfTargetSum(int[] candidateArr, int target, int nextIdx, boolean[] flagArr, int curSum) {
		counter.set(counter.get().intValue() + 1);
		// 递归终止条件
		if (curSum == target) {
			return filterSubset(candidateArr, flagArr);
		}
		if (nextIdx >= candidateArr.length) {
			return null;
		}

		// 处理当前层逻辑
		// 对于candidateArr[nextIdx]，有两种选择：a.包含 b.不包含
		// a.结果集中包含当前元素
		flagArr[nextIdx] = true;
		int[] result = findSubsetOfTargetSum(candidateArr, target, nextIdx + 1, flagArr,
				curSum + candidateArr[nextIdx]);
		if (result != null) {
			return result;
		}

		// b.结果集中不包含当前元素
		flagArr[nextIdx] = false;
		return findSubsetOfTargetSum(candidateArr, target, nextIdx + 1, flagArr, curSum);
	}

	private int[] filterSubset(int[] candidateArr, boolean[] flagArr) {
		int len = candidateArr.length;

		int size = 0;
		for (int i = 0; i < len; i++) {
			if (flagArr[i]) {
				size++;
			}
		}

		int[] subsetArr = new int[size];
		for (int i = len - 1; i >= 0; i--) {
			if (flagArr[i]) {
				subsetArr[--size] = candidateArr[i];
			}
		}
		return subsetArr;
	}

}
